/*
 * Copyright:  2018 smarabbit studio.
 *
 *  Licensed under the Confluent Community License; you may not use this file
 *  except in compliance with the License.  You may obtain a copy of the License at
 *
 *  http://www.confluent.io/confluent-community-license
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 *  WARRANTIES OF ANY KIND, either express or implied.  See the License for the
 *  specific language governing permissions and limitations under the License.
 *
 *  @作   者： 黄开晖 (117227773@qq.com)
 *  @日   期:  2021年5月29日
 */
package com.massyframework.beanskin.runtime.modular;

import java.util.Set;
import java.util.concurrent.CopyOnWriteArraySet;
import java.util.concurrent.ExecutorService;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.massyframework.beanskin.ModuleEvent;
import com.massyframework.beanskin.ModuleListener;
import com.massyframework.beanskin.runtime.ExecutorServiceAware;
import com.massyframework.beanskin.runtime.ModuleEventPublisher;
import com.massyframework.beanskin.util.exceptioncollect.ExceptionCollectUtils;

/**
 * 模块事件发布者
 * @author huangkh
 *
 */
public class DefaultModuleEventPublisher implements ModuleEventPublisher, ExecutorServiceAware{
	
	private Logger logger = LoggerFactory.getLogger(DefaultModuleEventPublisher.class);
	private Set<ModuleListener> listeners;
	private ExecutorService executorService;
	
	/**
	 * 
	 */
	public DefaultModuleEventPublisher() {
		this.listeners = new CopyOnWriteArraySet<>();
	}
	
	/**
	 * 发布模块事件
	 * @param event {@link ModuleEvent}
	 */
	public void applyEvent(ModuleEvent event) {
		for (ModuleListener listener: this.listeners) {
			try {
				listener.onEvent(event);
			}catch(Exception e) {
				if (logger.isErrorEnabled()) {
					logger.error(e.getMessage(), e);
				}
				ExceptionCollectUtils.addException(e);
			}
		}
	}
	
	/**
	 * 异步发送模块事件
	 * @param event {@link ModuleEvent}
	 */
	public void applyEventAsync(ModuleEvent event) {
		ExecutorService executor = this.executorService;
		if (executor != null) {
			executor.execute(new Task(event));
		}else {
			new Thread(new Task(event)).start();
		}
	}
	
	/**
	 * 添加事件监听器
	 * @param listener
	 */
	public void addListener(ModuleListener listener) {
		if (listener != null) {
			this.listeners.add(listener);
		}
	}
	
	/**
	 * 移除事件监听器
	 * @param listener
	 */
	public void removeListener(ModuleListener listener) {
		if (listener != null) {
			this.listeners.remove(listener);
		}
	}

	@Override
	public void setExecutorService(ExecutorService executorService) {
		this.executorService = executorService;
	}

	private class Task implements Runnable {
		private ModuleEvent event;
		
		public Task(ModuleEvent event) {
			this.event = event;
		}

		@Override
		public void run() {
			applyEvent(this.event);
		}
	}
}
